<?php

class MsgMode extends SiteMode {
    /** @return MsgMode */
    public static function init() {
        return parent::init();
    }
    //发送一则消息
    function send($user_id,$title,$content,$type = 'system'){
        $data['user_id']=$user_id;
        $data['title']=$title;
        $data['content']=$content;
        $data['type']=$type;
        $data['site_id']=$this->siteId;
        return $this->db->insert('msg',$data)==1 ? (int)$this->db->insertId():-1;
    }
    //消息详情
    function getDetail($id){
        $sql="SELECT * FROM `msg` WHERE `id`=? and site_id=?";
        return $this->db->getOne($sql,$id, $this->siteId);
    }
    /**
     * 消息列表
     * @param null $user_id
     * @param $type system|shop|recommend
     * @param int $rows
     * @param int $offset
     * @return list
     */
    function getList($user_id = null ,$type = null,$rows = 30,$offset = 0){
        $rows=(int)$rows;
        $offset=(int)$offset;
        $condition='';
        if(!empty($user_id)){
            $condition.=" AND (`user_id`=0 OR `user_id`=".(int)$user_id.")";
        }
        if(!empty($type)){
            $condition.=" AND `type`=".$this->db->quote($type);
        }
        $sql="SELECT SQL_CALC_FOUND_ROWS * FROM `msg` WHERE site_id=? $condition
              ORDER BY `create_time` DESC LIMIT $offset,$rows";
        return $this->db->getList($sql, $this->siteId);
    }
    //修改消息
    function modify($id,$user_id = null,$title = null,$content = null,$type = 'system'){
        $data['user_id']=$user_id;
        $data['title']=$title;
        $data['content']=$content;
        $data['type']=$type;
        $data['site_id']=$this->siteId;
        return $this->db->update('msg',$id,$data)==1;
    }

    function delete($id){
        return $this->db->delete('msg',$id)==1;
    }
} 